package com.sweet.mealon.face.daily.lock.reentrantlock.condition;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * faceDaily
 *
 * @Author: craizer.huang
 * @Date: 2021/5/5 9:49
 **/
public class ConditionDemo {
    private ReentrantLock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();

    /**
     * c1 等待
     */
    public void waitA(){
        lock.lock();

        try {
            System.out.println(String.format("%s get lock",Thread.currentThread().getName()));
            long now = System.currentTimeMillis();
            c1.await();
            long diff = System.currentTimeMillis() - now;
            System.out.println(String.format("%s invoke , spend %s",Thread.currentThread().getName(),String.valueOf(diff)));

        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }

    /**
     * c2 等待
     */
    public void waitB(){
        lock.lock();

        try {
            System.out.println(String.format("%s get lock",Thread.currentThread().getName()));
            long now = System.currentTimeMillis();
            c2.await();
            long diff = System.currentTimeMillis() - now;
            System.out.println(String.format("%s invoke , spend %s",Thread.currentThread().getName(),String.valueOf(diff)));

        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }

    public void signAllA(){
        lock.lock();
        try {
            System.out.println(String.format("%s invoke all",Thread.currentThread().getName()));
            c1.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void signAllB(){
        lock.lock();
        try {
            System.out.println(String.format("%s invoke all",Thread.currentThread().getName()));
            c2.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        ConditionDemo demo = new ConditionDemo();
        Thread a = new Thread(new ConditionThreadA(demo),"a");
        Thread b = new Thread(new ConditionThreadA(demo),"b");
        a.start();
        b.start();
        TimeUnit.SECONDS.sleep(2);
        demo.signAllA();
        TimeUnit.SECONDS.sleep(2);
        demo.signAllB();
        TimeUnit.SECONDS.sleep(2);


    }

}
